package com.adams.app.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.BaseColumns;
import android.support.v4.content.CursorLoader;
import android.util.Log;

import com.adams.app.model.Attractions;
import com.adams.app.utils.database.Column;
import com.adams.app.utils.database.SQLiteTable;

public class AttractionDataHelper extends BaseDataHelper {

	public AttractionDataHelper(Context context) {
		super(context);
	}

	@Override
	protected Uri getContentUri() {
		return DataProvider.SHOTS_CONTENT_URI;
	}

	private ContentValues getContentValues(Attractions attractions) {
		ContentValues values = new ContentValues();
		values.put(AttractionsDBInfo.ID, attractions.getId());
		values.put(AttractionsDBInfo.JSON, attractions.toJson());
		return values;
	}

	// 查询
	public Attractions query(long id) {
		Attractions attractions = null;
		Cursor cursor = query(null, AttractionsDBInfo.ID + "= ?",
				new String[] { String.valueOf(id) }, null);
		if (cursor.moveToFirst()) {
			attractions = Attractions.fromCursor(cursor);
		}
		cursor.close();
		return attractions;
	}

	// 快捷插入
	public void bulkInsert(List<Attractions> attractions) {
		ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
		for (Attractions attraction : attractions) {
			ContentValues values = getContentValues(attraction);
			contentValues.add(values);
		}
		ContentValues[] valueArray = new ContentValues[contentValues.size()];
		bulkInsert(contentValues.toArray(valueArray));
	}

	// 删除所有
	public int deleteAll() {
		synchronized (DataProvider.DBLock) {
			DataProvider.DBHelper mDBHelper = DataProvider.getDBHelper();
			SQLiteDatabase db = mDBHelper.getWritableDatabase();
			int row = db.delete(AttractionsDBInfo.TABLE_NAME, null, null);
			return row;
		}
	}

	// 获取加载器
	public CursorLoader getCursorLoader() {
		if(null == getContext()) {
			Log.i("CursorLoader", "null?");
		} else {
			Log.i("CursorLoader", "not null");
		}
		return new CursorLoader(getContext(), getContentUri(), null, null,
				null, AttractionsDBInfo._ID + " ASC");
	}

	public static final class AttractionsDBInfo implements BaseColumns {
		private AttractionsDBInfo() {
		}

		public static final String TABLE_NAME = "attractions";

		public static final String ID = "id";

		public static final String JSON = "json";

		public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME)
				.addColumn(ID, Column.DataType.INTEGER).addColumn(JSON,
						Column.DataType.TEXT);
	}
}
